<?php
/**
 * 公共控制器
 * 主要用于权限验证
 */
class CommonApp extends Controller{
	
	/**
	 * 初始化
	 * by huanran.zhao
	 */
	public function _initialize() {
		C('SHOW_PAGE_TRACE',(My::arr2var($_GET,'debug')=='true' OR C('SHOW_PAGE_TRACE')==true)?true:false);//debug调试
		//print_r(My::user());
		define('URL', $_SERVER['REQUEST_URI']);	//当前url
		define('URL_', (My::user('URL_'))?My::user('URL_'):empty($_SERVER['HTTP_REFERER'])?"":$_SERVER['HTTP_REFERER']);//上一页面url
		self::checkLogin();//登录验证 -> 访问权限验证
		self::setcookie();//设置相关cookie变量供前端用
	}
	
	/**
	 * 设置相关cookie变量供前端用
	 */
	private function setcookie(){
		setcookie("__ROOT__", __ROOT__,null,__ROOT__);
		setcookie("__PROJECT__", __PROJECT__,null,'/');
	}
	
	/**
	 * 跳转函数(兼容函数)
	 * by huanran.zhao
	 */
	public function ajaxReturn($statusCode, $message, $callbackType = '', $forwardUrl = '', $data='') {
		//404页面,使用方法$this->ajaxReturn(404,'找不到页面');
		if($statusCode==404){
			$this->assign('title',$message);
			$this->display('include/404');
			exit();
		}
		//ajaxsubmit方式提交的表单(表单验证方式)
		if(My::is_ajax()){
			$jsonData = array(
								'statusCode' => $statusCode,
								'message' => $message,
								'forwardUrl' => $forwardUrl,
								'data' => $data
							 );
			exit(json_encode($jsonData));
		}
		//正常方式页面跳转
		else{
			if(isset($_GET['URL'])) $URL=$_GET['URL'];//将get赋值给post
			if(isset($_POST['URL_'])) $URL_=$_POST['URL_'];//将get赋值给post
			//有传参时,强行按这个跳转url=$url
			if(!empty($url)) $URL=$URL_=$url;
			if(My::user('URL_')) $URL_=My::user('URL_');
			//默认
			if(empty($URL)) $URL = URL;
			if(empty($URL_)) $URL_ = URL_;
			
			$this->assign("text",$message);
			$this->assign("time",2);
			if($statusCode==200){
				unset($_SESSION['URL_']);
				if(isset($_SESSION['token_key']) AND isset($_SESSION['token'][$_SESSION['token_key']])) unset($_SESSION['token'][$_SESSION['token_key']]);//200时销毁Token变量
				$this->assign("url",$URL_);//成功:返回上一页面URL_
			}else{
				$_SESSION['URL_'] = $URL_;
				$this->assign("url",$URL);//失败:返回上一页面
			}
			$this->display('jump');
		}
	}
	
	/**
	 * 检查会话是否超时
	 */
	public function checkLogin(){
		// 可公共访问的控制器及相关的Action
		$controllerName = strtolower(CONTROLLER_NAME);
		$actionName = strtolower(ACTION_NAME);
		$authArr = array(
			//'app'=>array('update','download'),
		);
		if(array_key_exists($controllerName, $authArr))
		{
			$accessArr = $authArr[$controllerName];
			if(in_array($actionName, $accessArr)) return true;
		}
		//判断登录
		if(!My::user('userid') OR !My::user('username')){
			//ajaxsubmit提交时不跳转到登陆页,直接提示就行
			if(My::is_ajax())
				$this->ajaxReturn(300,'登录超时,请重新登陆!');
			else
				redirect(Router::encodeUrl('index.php?app=public&act=login'));
		}else{
		    $this->assign("username",My::user('username'));
		}
		//设置登录状态
		//M('api.login')->setLoginState(My::user('userid'));
		//菜单访问权限验证
		$this->assign('menu', M('menu')->getMenu());//左菜单
		$this->checkAuth();//访问权限验证
	}
	
	/**
	 * 访问权限验证
	 */
	private function checkAuth(){
		//如果是超级管理员，跳过权限验证
		if(My::user('role_id')==1){
			M('visit')->setVisitLog();//记录访问日志
			return true;
		}
		//普通用户
		$url = CONTROLLER_NAME.'/'.ACTION_NAME;
		$myMenu = M('menu')->getMenu(true);
		$isAccess = self::authRoleAccess($url, $myMenu);
		if(!$isAccess){
			$message = "对不起，你没有权限执行此操作！<br>(".CONTROLLER_NAME."/".ACTION_NAME.")";
			if(My::is_ajax())
				$this->ajaxReturn(300, $message);
			else
				$this->ajaxReturn(404, $message);
		}else{//访问成功
			M('visit')->setVisitLog();//记录访问日志
		}
	}
	
	/**
	 * 验证是否有权限访问
	 */
	private function authRoleAccess($url, $modules){
		//print_r($modules);echo $url.'--'.$modules;exit;
		$isAccess = false;
		$url = strtolower($url);
		$isFunctionsDelete = $url==='functions/delete';//是否删除操作
		$outside = array(
						'index/index',// 默认任何角色都可以访问主页
						);
		if(in_array($url,$outside))
			$isAccess = true;
		elseif(is_array($modules)){
			foreach($modules as $key=>$module){
				$module_url = str_replace('index.php?','',isset($module['params']['link'])?strtolower($module['params']['link']):'');
				$module_url = str_replace('&amp;','&',$module_url);
				parse_str($module_url,$module_array);//分析url
				$module_array['act'] = !empty($module_array['act'])?$module_array['act']:'index';//action为空时,默认index
				$module_url=(isset($module_array['app'])?$module_array['app']:'').'/'.(isset($module_array['act'])?$module_array['act']:'');
				//print_r($module_array).'<br>';
				//echo $url.'---'.$module_url.'<br>';
				if($url==$module_url and (!$isFunctionsDelete or My::arr2var($_POST,'table')==My::arr2var($module_array,'table'))){
					$isAccess = true;
					break;
				}
			}
		}
		/////白名单 S
		$temp_=explode('/', $url);
		if($temp_[0]=="functions" and !$isFunctionsDelete) $isAccess = true;//functions控制器
		//菜单权限配置文件
		$menuLimit = include(ROOT_DIR.'Config/MenuLimit.php');
		if(is_array($menuLimit))
		foreach($menuLimit as $key=>$value){
			$continue = false;
			//判断$key中的url参数是否符合 当前网址
			parse_str($key,$keyParam);
			if(is_array($keyParam))
			foreach($keyParam as $k=>$v){
				if(!I("request.{$k}") OR strtolower(I("request.{$k}"))!=strtolower($v)){
					$continue = true;
					break;
				}
			}
			if($continue==true)	continue;
			//进而判断$value中的各个url是否符合条件
			if(is_array($value))
			foreach($value as $vv){
				$continue = false;
				parse_str($vv,$valueParam);
				if(is_array($valueParam))
				foreach($valueParam as $kkk=>$vvv){
					if(!I("request.{$kkk}") OR strtolower(I("request.{$kkk}"))!=strtolower($vvv)){
						$continue = true;
						break;
					}
				}
				//如$continue为false则说明当前url符合条件,权限改为OK,直接退出
				if($continue==false){
					$isAccess = true;
					break;
				}
			}
		}
		return $isAccess;
	}
	
	/**
	 * 验证表单函数
	 * @param string $param (分类id 或 表单模型唯一名称) //分类ID:相应分类ID下的指向表单模型 (两参数二选一)
	 */
	public function verify($param=''){//如(128 或 form_category)
		//得到分类id
		if(My::is_id($param))
			$cat_id = $param;
		elseif(My::is_item($param))
			$cat_id = M('category')->item2id($param);
		else
			return false;
		//开始验证
		$ok = Form::verify($cat_id);
		if($ok!==true) $this->ajaxReturn(300,json_encode($ok));
	}

}